from google.appengine.ext   import webapp
from google.appengine.ext   import db
from ironcap                import cache
from ironcap.cms.models     import Page
from ironcap.cms.services   import result
from ironcap.serialization  import jsonserializer

#=========================================================================
# ironcap.cms.backend.pages.handler
#=========================================================================

class handler(object):
	
	class index(webapp.RequestHandler):
		""" lists pages 
			params : 
				null
		"""
		def post(self):
			self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
			data = []
			for n in Page.all().order('url'):
				data.append({'url': n.url, 'key' : str(n.key())})
			self.response.out.write(result.json(data))
	
	class get(webapp.RequestHandler):
		""" opens a page 
			params : 
				url:string
		"""
		def post(self):
			self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
			params = jsonserializer.deserialize(self.request.body)
			
			#validate
			if not params:
				self.response.out.write(result.json(None, False, 'no data'))
				return
			if not 'key' in params:
				self.response.out.write(result.json(None, False, 'key is required'))
				return
			
			# output
			page = Page.get(params['key'])
			if page:
				self.response.out.write(result.json({'key'       : str(page.key()),
													 'url'       : page.url,
													 'mime'      : page.mime,
													 'template'  : str(page.template),
													 'code'      : str(page.code)}))
				return
			self.response.out.write(result.json(None, False, 'page not found'))
	
	class create(webapp.RequestHandler):
		""" creates a page 
			params : 
				url:string
		"""	
		def post(self):
		
			cache.shared.flush() # flush entire cache ?
		
			self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
			params = jsonserializer.deserialize(self.request.body)
			
			#validate
			if not params:
				self.response.out.write(result.json(None, False, 'no data'))
				return
			if not 'url' in params:
				self.response.out.write(result.json(None, False, 'url is required'))
				return
			test = Page.get_by_url(params['url'])
			if test:
				self.response.out.write(result.json(None, False, 'the url ' + params['url'] + ' already exists.'))
				return

			# defaults
			if not 'mime' in params:
				params['mime'] = 'text/plain'
			if not 'template' in params:
				params['template'] = '<html></html>'
			if not 'template' in params:
				params['code'] 	   = ''
				
			# output
			page = Page.get_by_url(params['url'])
			if page:
				self.response.out.write(result.json(None, False, 'url already exists'))
			else:
				page   = Page.create(**params)
				self.response.out.write(result.json({'key'       : str(page.key()),
													 'url'       : page.url,
													 'mime'      : page.mime,
													 'template'  : str(page.template),
													 'code'      : str(page.code)}, True))
				
			
	class update(webapp.RequestHandler):
		""" creates or updates a page
			params : 
				name    :string   
				url     :string     
				mime    :string    
				template:string 
				code    :string    
		"""
		def post(self):	
		
			cache.shared.flush() # flush entire cache ?
			
			self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
			params = jsonserializer.deserialize(self.request.body)
			
			#validate
			if not params:
				self.response.out.write(result.json(None, False, 'no data'))
				return
			if not 'key' in params:
				self.response.out.write(result.json(None, False, 'key is required'))
				return

			#fetch page
			page = Page.get(params['key'])
			if page:
				if 'url' in params: # additional validate on url
					test = Page.get_by_url(params['url'])
					if test:
						if not test.url == page.url:
							self.response.out.write(result.json(None, False, 'this url is already in use.'))
							return	
							
				page.update(**params)
				cache.local.delete('page', params['key']) # force module recompilation
				
				self.response.out.write(result.json({'key'       : params['key'],
													 'url'       : page.url,
													 'mime'      : page.mime,
													 'template'  : str(page.template),
													 'code'      : str(page.code)}, True))
				return

			self.response.out.write(result.json(None, False, 'page not found'))
	
	class delete(webapp.RequestHandler):
		""" deletes a page 
			params : 
				url:string
		"""
		def post(self):
		
			cache.shared.flush() # flush entire cache ?
		
			self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
			params = jsonserializer.deserialize(self.request.body)
			
			#validate
			if not params:
				self.response.out.write(result.json(None, False, 'no data'))
				return
			if not 'key' in params:
				self.response.out.write(result.json(None, False, 'key is required'))
				return
				
			page = Page.get(params['key'])
			if page:
				cache.instance.delete('page', params['key']) # delete unnessasary module
				page.delete()
				self.response.out.write(result.json(None, True))
				return
				
			self.response.out.write(result.json(None, False, 'page not found'))